<template>
  <base-modal
    :title="$t('task.taskTypes.allot.batchAllot')"
    :show.sync="visible"
    width="600px"
    class="batch-allot-dialog"
    append-to-body
  >
    <div class="dialog-body">
      <div class="dialog-body-content">
        {{$t('task.tip.allotTaskTip3', {num: tasksCount})}}
        <task-allot-select 
          ref="TaskAllotSelect"
          :type-options="typeOptions"
          :task-config="taskConfig"
          @update:type="changeAllotType"
          @update:synergies="changeSynergies"
          @update:executors="changeExecutors"
        >
        </task-allot-select>
      </div>
    </div>
    <div class="dialog-footer" slot="footer">
      <el-button :disabled="loading" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" :disabled="loading" @click="submit">{{$t('common.base.makeSure')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* Api */
import * as TaskApi from '@src/api/TaskApi.ts';
/** components */
import TaskAllotSelect from '@src/modules/task/edit/components/TaskAllotSelect/TaskAllotSelect.vue'

export default {
  name: 'batch-allot-dialog',
  props: {
    typeOptions: {
      type: Array,
      default: () => ['pool', 'normal', 'auto']
    },
    taskIdList: {
      type: Array, // ids
      default: () => [],
    }
  },
  data: () => {
    return {
      visible: false,
      taskConfig: {},
      loading: false,

      allotType: 'normal',
      synergies: [],
      executors: [],
    };
  },
  computed: {
    tasksCount() {
      return this.taskIdList.length;
    }
  },
  methods: {
    /* 更改派单类型 */
    changeAllotType(value) {
      this.allotType = value;
    },
    /* 更改协同人 */
    changeSynergies(value) {
      this.synergies = value;
    },
    /* 更改协同人 */
    changeExecutors(value) {
      this.executors = value;
    },
    /** 工单批量指派 */
    async submit() {
      const { taskIdList, synergies, executors, allotType, tasksCount, $platform } = this;
      
      if (executors.length !== 1 && allotType === 'normal') {
        $platform.alert(this.$t('common.placeholder.selectSomething', {0: this.$t('task.executor')}));
        return;
      }
      
      let action = TaskApi.batchAllotTask;
      
      if(allotType === 'pool') {
        action = TaskApi.batchAllotPool;
      }
      if(allotType === 'auto') {
        action = TaskApi.batchAllotAuto;
      }
      
      try {
        let params = {
          executorId: executors.length > 0 ? executors[0].userId : '',
          synergiesIds: synergies.join(','),
          taskIds: taskIdList.join(',')
        }
        
        this.loading = true;
        const FormId = window.frameElement.getAttribute('id');
        let res = await action(params);
        
        if(res.status == 0) {
          let succMap = res.data.succ;
          let exeInSynOfTaskOrEvent;
          succMap.forEach(item => {
            exeInSynOfTaskOrEvent = item.exeInSynOfTaskOrEvent;
          });
          
          let exeInSynMes = '';
          if(exeInSynOfTaskOrEvent){
            exeInSynMes = this.$t('common.modal.ALLOT_SYNERGY_MASSAGE');
          }
          if(allotType === 'pool' || allotType === 'auto'){
            $platform.alert(`${this.$t('common.modal.BatchAllotNotExecutorSuccessMessage', {successCount: tasksCount, synergyUsers: synergies.join(',') == '' ? '无' : synergies.join(',')})}\n${ exeInSynMes}`);
          }else{
            $platform.alert(`${this.$t('common.modal.BatchAllotExecutorSuccessMessage', {successCount: tasksCount, executorUsers: executors[0].displayName, synergyUsers: synergies.join(',') ? '无' : synergies.join(',')})}\n${ exeInSynMes}`);
          }
          $platform.refreshTab(FormId)
        }else if(res.status == 1){
          let message = res.message;
          if(res.data != null){
            let failMap = res.data.fail;
            message += '： ';
            failMap.forEach((item, idx)=>{
              message += item.taskNo;
              if(idx != (res.data.fail.length - 1)){
                message += ',';
              }
            });
            message += this.$t('common.modal.BatchAllotPartSuccessMessage', {successCount: res.data.succ.length});
            $platform.alert(message);
          }
          $platform.refreshTab(FormId)
        }else {
          $platform.alert(res.message);
        }
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    openDialog(taskConfig = {}) {
      this.visible = true
      this.taskConfig = taskConfig || {}
    },
  },
  components: {
    [TaskAllotSelect.name]: TaskAllotSelect
  }
};
</script>

<style lang="scss" scoped>
.batch-allot-dialog {
  padding: 0 10px;
  .dialog-body {
    padding: 15px;
    padding-bottom: 30px;
    margin: 10px auto;
    width: 96%;
    &-content {
      font-size: 12px;
      background-color: #d9edf7;
      padding: 10px 25px;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }

  ::v-deep .task-allot-select-synergies{
    background-color: #fff;
  }
}
</style>
